
package com.crm.dataReceive.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.domain.HitPackage;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.IHitPackageService;
import com.crm.dataReceive.domain.Customer;
import com.crm.dataReceive.domain.jkyq;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.utils.AesUtils;
import com.ruoyi.common.utils.Base64Util;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 绿信集团流量接口
 */


@RestController
@RequestMapping("/jk")
public class JkyqController {
    public static final org.slf4j.Logger log = LoggerFactory.getLogger("CustPrefix8CheckInfo");

//    private final static String AES_KEY = "20df373ae1c04bbd9c77e30695ada7e8";
    private final static String channelSource = "jk";
    @Autowired
    private IHitPackageService hitPackageService;
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;
    @Autowired
    private ISysConfigService baseSysConfigService;
    @Anonymous
    @PostMapping("check/tenant/{tenantId}")
    @ResponseBody
    public Map<String, Object> check(@RequestBody jkyq req) {
        try {
            String AES_KEY = baseSysConfigService.getItemValueByItemKey(ConfigConstant.JKYQ_AES_KEY,"32e326b5053bc97b895f2c14c228af82");
            if (StringUtils.isBlank(req.getData())) {
                return jkyqResult("9999", "data数据为空");
            }
            String realData = Base64Util.decryptAes(req.getData(), AES_KEY);
            if (StringUtils.isBlank(realData)) {
                return jkyqResult("9999", "解密失败");
            }
            log.info("jkyq解密结果：{}", realData);
            JSONObject data = JSONObject.parseObject(realData);
            jkyq checkInfo = JSON.toJavaObject(data, jkyq.class);
            if (checkInfo.getPhoneNo().length() != 32) {
                return jkyqResult("9999", "非32位md5格式");
            }
            if (StringUtils.isBlank(checkInfo.getCity())) {
                return jkyqResult("9999", "城市字段缺失");
            }
            String city = checkInfo.getCity();
            city = city == null ? "" : city.replace("市", "").replace("地区", "");

            HitPackage hitPackage = new HitPackage();
            hitPackage.setMobileMd5(checkInfo.getPhoneNo());
            List<HitPackage> custs= hitPackageService.selectHitPackageList(hitPackage);
            if (CollectionUtils.isNotEmpty(custs)) {
                return jkyqResult("9999", "已存在该用户");
            }

            return jkyqResult("0000", "接受该用户");
        } catch (Exception e) {
            log.error("jkyq异常：" + e.getMessage());
            return jkyqResult("9999", "api处理异常");
        }
    }
    @Anonymous
    @PostMapping("apply/tenant/{tenantId}")
    @ResponseBody
    public Map<String, Object> apply(@RequestBody jkyq req) {
        Map<String, Object> resMap = new HashMap<>();
        try {
            if (StringUtils.isBlank(req.getData())) {
                return jkyqResult("9999", "data数据为空");
            }
            String AES_KEY = baseSysConfigService.getItemValueByItemKey(ConfigConstant.JKYQ_AES_KEY,"32e326b5053bc97b895f2c14c228af82");
            String realData = Base64Util.decryptAes(req.getData(), AES_KEY);
            if (StringUtils.isBlank(realData)) {
                return jkyqResult("9999", "解密失败");
            }
            log.info("jkyq解密结果：{}", realData);
            JSONObject data = JSONObject.parseObject(realData);
            jkyq checkInfo = JSON.toJavaObject(data, jkyq.class);

            String city = checkInfo.getCity();
            city = city == null ? "" : city.replace("市", "").replace("地区", "");
            Customer customer = new Customer();
            customer.setMobile(checkInfo.getPhoneNo());
            customer.setCustName(checkInfo.getCustName());
            customer.setCity(city);
            int loanAmount = 0;
            if ("1".equals(checkInfo.getLoanAmount())) {
                loanAmount = 30000;
            } else if ("2".equals(checkInfo.getLoanAmount())) {
                loanAmount = 50000;
            } else if ("3".equals(checkInfo.getLoanAmount())) {
                loanAmount = 100000;
            } else if ("4".equals(checkInfo.getLoanAmount())) {
                loanAmount = 200000;
            } else if ("5".equals(checkInfo.getLoanAmount())) {
                loanAmount = 500000;
            }
            customer.setApplyLimit(new BigDecimal(loanAmount));
            customer.setSex(checkInfo.getSex());
            customer.setAge(checkInfo.getAge() == null ? 0L : Long.valueOf(checkInfo.getAge()));
            CustInfo custInfo = new CustInfo();
            ObjectUtil.copyProperties(customer, custInfo);

            custInfo.setRepeatFlag("0");
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            String md5value = Md5Encrypt.md5(customer.getMobile());
            custInfo.setMd5val(md5value);
            custInfo.setDistributeId(-1L);


            if("H4131042875588".equals(req.getMerchantNo())) {
                //全量：
                custInfo.setChannelSource("jk001");
            }else{
                // 房 金：H3989685395594
                custInfo.setChannelSource("jk0010");
            }
            if("0".equals(checkInfo.getProvidentFund())){
                custInfo.setHasFund("0");
            }else {
                custInfo.setHasFund("1");
            }
            if("0".equals(checkInfo.getSocialSecurity())){
                custInfo.setHasSocial("0");
            }else {
                custInfo.setHasSocial("1");
            }
            if("0".equals(checkInfo.getCar())){
                custInfo.setHasCar("0");
            }else {
                custInfo.setHasCar("1");
            }

            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            // 客户申请信息前置检查
            Map<String, Object> checkResult = custInfoService.checkCustInfo(custInfo, log);
            if (MapUtils.getIntValue(checkResult, "errorNo", -1) != 0) {
                return jkyqResult("9999", MapUtils.getString(checkResult, "errorInfo", ""));
            }
            // 随机分配
            Long[] orgIds = custInfoService.getOrgIdsByCity(custInfo.getCity());
            boolean isSucceed = custInfoService.dealCustRandomly(custInfo, orgIds, true, false, log);
            if (isSucceed) {
                if (StringUtils.isNotBlank(custInfo.getRemark())) {
                    // 自动生成一条备注
                    CustCommentRecord record = new CustCommentRecord();
                    record.setCustId(custInfo.getId());
                    record.setEmpId(null);
                    record.setEmpName("系统自动备注");
                    record.setRemark(custInfo.getRemark());
                    record.setType(1L);
                    record.setType2(1L);
                    record.setCreateTime(new Date());
                    custCommentRecordService.insertCustCommentRecord(record);
                }
            } else {
                return jkyqResult("9999", "线索接收API请求申请异常");
            }
        } catch (Exception e) {
            log.error("jkyq异常：" + e.getMessage());
            return jkyqResult("9999", "api请求异常：" + e.getMessage());
        }
        return jkyqResult("0000", "线索接收成功");
    }

    private Map<String, Object> jkyqResult(String code, String msg) {
        Map<String, Object> resMap = new HashMap<>(2);
        resMap.put("dealStatus", code);
        resMap.put("dealDesc", msg);

        return resMap;
    }
}

